//
//  BaseDB.m
//  数据增删查改
//
//  Created by app05 on 15/7/21.
//  Copyright (c) 2015年 app. All rights reserved.
//

#import "BaseDB.h"

@implementation BaseDB

-(NSString *)filePath
{
    NSString *filePath=@"/Users/app05/Desktop/data.plist";
    return filePath;
}
-(void)creatTable:(NSString *)sql
{
    sqlite3 *sqlite=nil;
    
    if (sqlite3_open([self.filePath UTF8String], &sqlite)!=SQLITE_OK) {
        NSLog(@"打开数据库失败");
        return;
    }
    
    char *error=nil;
    if (sqlite3_exec(sqlite, [sql UTF8String], NULL, NULL, &error) !=SQLITE_OK) {
        NSLog(@"创建失败：%s",error);
        sqlite3_close(sqlite);
    }
    
    sqlite3_close(sqlite);
}

-(BOOL)dealData:(NSString *)sql paramsarray:(NSArray *)params
{
    sqlite3*sqlite=nil;
    sqlite3_stmt *stmt=nil;
    
    if (sqlite3_open([self.filePath UTF8String], &sqlite)!=SQLITE_OK) {
        NSLog(@"打开数据库失败");
        
        sqlite3_close(sqlite);
        return NO;
    }
    
    if (sqlite3_prepare_v2(sqlite, [sql UTF8String], -1, &stmt, NULL)!=SQLITE_OK) {
        NSLog(@"SQL数据编译失败");
        NSLog(@"Error:%s",sqlite3_errmsg(sqlite));
        sqlite3_close(sqlite);
        return NO;
    }
    
    for (int i=0; i<params.count; i++) {
        NSString*value=[params objectAtIndex:i];
        sqlite3_bind_text(stmt, i+1, [value UTF8String], -1, NULL);;
    }
    
    if (sqlite3_step(stmt)==SQLITE_ERROR) {
        NSLog(@"SQL语句执行失败");
        sqlite3_close( sqlite);
        return NO;
    }
    
    sqlite3_finalize(stmt);
    sqlite3_close(sqlite);
    
    return YES;
}

-(NSMutableArray *)selectData:(NSString *)sql column:(int)number
{
    sqlite3*sqlite=nil;
    sqlite3_stmt *stmt=nil;
    
    if (sqlite3_open([self.filePath UTF8String], &sqlite)!=SQLITE_OK) {
        NSLog(@"打开数据库失败");
        sqlite3_close(sqlite);
        return nil;
    }
    if (sqlite3_prepare_v2(sqlite, [sql UTF8String], -1, &stmt, NULL)!=SQLITE_OK) {
        NSLog(@"sql语句编译失败");
        sqlite3_close(sqlite);
        
        return nil;
    }
    
    int result=sqlite3_step(stmt);
    NSMutableArray *data=[NSMutableArray array];
    while (result==SQLITE_ROW) {
        NSMutableArray *row=[NSMutableArray arrayWithCapacity:number];
        for (int i =0; i<number; i++) {
            char *culumnText=(char*)sqlite3_column_text(stmt, i);
            NSString *string=[NSString stringWithCString:culumnText encoding:NSUTF8StringEncoding];
            [row addObject:string];
        }
        [data addObject:row];
        
        result=sqlite3_step(stmt);
    }
    
    sqlite3_finalize(stmt);
    sqlite3_close(sqlite);
    
    return  data;
}
@end
